<?php
declare (strict_types=1);

namespace app\common\model;

use think\facade\Db;

class OrderProduct extends Base
{
    protected $name = 'order_product';

    public function p()
    {
        return $this->hasOne(Area::class, 'code', 'province')->field('code,province as title');
    }

    public function c()
    {
        return $this->hasOne(Area::class, 'code', 'city')->field('code,city as title');
    }

    public function d()
    {
        return $this->hasOne(Area::class, 'code', 'district')->field('code,district as title');
    }

    public static function add($products, $order_id)
    {
        try {
            $orders = [];
            foreach ($products as $k => $v) {
                $product = Product::where('id', $v['id'])->field('icon')->find();
                $orders[$k]['order_id'] = $order_id;
                $orders[$k]['pid'] = $v['id'];
                $orders[$k]['product_title'] = $v['title'];
                $orders[$k]['num'] = $v['num'];
                $orders[$k]['product_image'] = $product->getData('icon');
                $orders[$k]['price'] = $v['vip_price'];
            }
            if (!empty($orders)) {
                Db::name('order_product')->insertAll($orders);
            }

            return ['code' => 1, 'msg' => 'success'];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }

    }

    public function getProductImageAttr($value)
    {
        return handleImg($value);
    }
}
